package com.njworkorder.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.njworkorder.DTO.AssignmentAddDto;
import com.njworkorder.DTO.SelectDTO.SelectAssignmentDto;
import com.njworkorder.Entity.*;
import com.njworkorder.Entity.Dictionary;
import com.njworkorder.Mapper.*;
import com.njworkorder.Service.*;
import com.njworkorder.Utils.NoCode;
import com.njworkorder.Utils.Result;
import com.njworkorder.Utils.ResultUtil;
import com.njworkorder.VO.*;
import com.njworkorder.VO.AssignmentProgressVos.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Tag(name = "任务管理", description = "任务管理相关接口")
@RestController
@RequestMapping("/assignment")
public class AssignmentController {

    private final AssignmentWithDiseaseService awdService;
    private final AssignmentMapper assignmentMapper;
    private final AssignmentService assignmentService;
    private final AssignmentWithDiseaseMapper assignmentWithDiseaseMapper;
    private final EngineeringQualityInfoService engineeringQualityInfoService;
    private final BillOfQuantitiesMapper billOfQuantitiesMapper;

    private final BillOfQuantitiesService billOfQuantitiesService;
    private final BopWithDrService bopWithDrService;
    private final EqiWithDrService eqiWithDrService;
    private final DiseaseService diseaseService;
    private final AssignmentApprovalHistoryService assignmentApprovalHistoryService;
    private final EqiWithTpMapper eqiWithTpMapper;
    private final SectionService sectionService;

    public AssignmentController(AssignmentService assignmentService, AssignmentMapper assignmentMapper,
                                AssignmentWithDiseaseService awdService, AssignmentWithDiseaseMapper assignmentWithDiseaseMapper,
                                BillOfQuantitiesMapper billOfQuantitiesMapper, BopWithDrService bopWithDrService,
                                EqiWithDrService eqiWithDrService, AssignmentApprovalHistoryService assignmentApprovalHistoryService,
                                DiseaseService diseaseService, EqiWithTpMapper eqiWithTpMapper,BillOfQuantitiesService billOfQuantitiesService,
                                SectionService sectionService,EngineeringQualityInfoService engineeringQualityInfoService) {
        this.assignmentService = assignmentService;
        this.assignmentMapper = assignmentMapper;
        this.awdService = awdService;
        this.assignmentWithDiseaseMapper = assignmentWithDiseaseMapper;
        this.billOfQuantitiesMapper = billOfQuantitiesMapper;
        this.bopWithDrService = bopWithDrService;
        this.eqiWithDrService = eqiWithDrService;
        this.diseaseService = diseaseService;
        this.assignmentApprovalHistoryService = assignmentApprovalHistoryService;
        this.eqiWithTpMapper = eqiWithTpMapper;
        this.sectionService = sectionService;
        this.engineeringQualityInfoService = engineeringQualityInfoService;
        this.billOfQuantitiesService = billOfQuantitiesService;
    }

    @Transactional
    @Operation(summary = "添加任务")
    @PostMapping("/addInfo")
    public Result<String> addInfo(@RequestBody AssignmentAddDto assignmentAddDto, @RequestHeader("Create-Ap-Id") String createApId) {

        String assignmentId = UUID.randomUUID().toString();

        String[] arr = assignmentAddDto.getDiseaseRegistrationIds();
        List<AssignmentWithDisease> diseaseRegistrationIds = getDiseaseRegistrationIds(arr, assignmentId);
        boolean b = awdService.saveBatch(diseaseRegistrationIds);

        Assignment assignment = new Assignment();
        BeanUtils.copyProperties(assignmentAddDto, assignment);
        if (assignmentAddDto.getTaskOrderNumber().isEmpty() || assignmentAddDto.getTaskOrderNumber().isBlank()) {
            String numNew = assignmentService.getTaskOrderNumber();
            String value = NoCode.values()[Integer.parseInt(assignmentAddDto.getDiseaseModule()) - 1].toString();
            assignment.setTaskOrderNumber(NoCode.RW + value + numNew);
        }

        assignment.setId(assignmentId);
        assignment.setCreateApId(createApId);

        boolean save = assignmentService.save(assignment);
        if (save && b) {
            assignmentApprovalHistoryService.saveApprovalHistory(0, assignmentAddDto.getRemark(), createApId, assignmentId);
            return ResultUtil.success("添加成功");
        }
        return ResultUtil.fail("添加失败");
    }

    @Operation(summary = "根据病害模块获取任务单号")
    @GetMapping("/getTaskOrderNumber")
    public Result<Map<String,String>> getTaskOrderNumber(@Schema(description = "病害模块") @RequestParam(value = "diseaseModule") String diseaseModule){
        String numNew = assignmentService.getTaskOrderNumber();
        String value = NoCode.values()[Integer.parseInt(diseaseModule) - 1].toString();
        Map<String,String> map = new HashMap<>();
        map.put("taskOrderNumber",NoCode.RW + value + numNew);
        return ResultUtil.success(map);
    }

    public List<AssignmentWithDisease> getDiseaseRegistrationIds(String[] ids, String assignmentId) {
        List<AssignmentWithDisease> AWDList = new ArrayList<>();
        for (String s : ids) {
            if (!s.isBlank()) {
                AssignmentWithDisease AWD = new AssignmentWithDisease();
                AWD.setAssignmentId(assignmentId);
                AWD.setDiseaseId(s);
                AWD.setStatus("2");
                AWDList.add(AWD);
            }
        }
        return AWDList;
    }

    @Operation(summary = "根据id修改任务信息")
    @PostMapping("/updateInfoById/{id}")
    public Result<String> updateInfoById(@RequestBody AssignmentAddDto assignmentUpdateDto, @PathVariable("id") String id) {

        LambdaQueryWrapper<Assignment> wrapperQ = new LambdaQueryWrapper<>();
        wrapperQ.eq(Assignment::getId, id).eq(Assignment::getAuditStatus, 1);
        long count = assignmentService.count(wrapperQ);
        if (count > 0) {
            return ResultUtil.fail("已审核的任务不能修改");
        }

        LambdaQueryWrapper<AssignmentWithDisease> wrapper = new LambdaQueryWrapper<AssignmentWithDisease>()
                .eq(AssignmentWithDisease::getAssignmentId, id);
        awdService.remove(wrapper);

        String[] arr = assignmentUpdateDto.getDiseaseRegistrationIds();
        List<AssignmentWithDisease> diseaseRegistrationIds = getDiseaseRegistrationIds(arr, id);
        awdService.saveBatch(diseaseRegistrationIds);

        Assignment assignment = new Assignment();
        BeanUtils.copyProperties(assignmentUpdateDto, assignment);
        if (assignmentUpdateDto.getTaskOrderNumber().isEmpty() || assignmentUpdateDto.getTaskOrderNumber().isBlank()) {
            String numNew = assignmentService.getTaskOrderNumber();
            String value = NoCode.values()[Integer.parseInt(assignmentUpdateDto.getDiseaseModule()) - 1].toString();
            assignment.setTaskOrderNumber(NoCode.RW + value + numNew);
        }

        assignment.setId(id);
        boolean update = assignmentService.updateById(assignment);
        if (update) {
            return ResultUtil.success("修改成功");
        }
        return ResultUtil.fail("修改失败");
    }

    @Operation(summary = "根据id删除任务信息")
    @PostMapping("/deleteById")
    public Result<String> deleteById(@RequestParam("id") String id) {
        boolean remove = assignmentService.removeById(id);

        LambdaQueryWrapper<AssignmentWithDisease> wrapper = new LambdaQueryWrapper<AssignmentWithDisease>()
                .eq(AssignmentWithDisease::getAssignmentId, id);
        awdService.remove(wrapper);


        if (remove) {
            return ResultUtil.success("删除成功");
        }
        return ResultUtil.fail("删除失败");
    }

    @Operation(summary = "根据id查询任务信息")
    @GetMapping("/getById")
    public Result<AssignmentDetailsVo> getById(@RequestParam("id") String id) {

        MPJLambdaWrapper<Assignment> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(Assignment.class)
                .leftJoin(InspectionRegistration.class, InspectionRegistration::getId, Assignment::getInspectionInfo)
                .leftJoin(Workspace.class, Workspace::getId, InspectionRegistration::getWorkspaceId, ext ->
                        ext.selectAs(Workspace::getWorkspaceName, AssignmentDetailsVo::getWorkspaceName))
                .leftJoin(Section.class, Section::getId, InspectionRegistration::getSectionId, ext ->
                        ext.selectAs(Section::getSectionName, AssignmentDetailsVo::getSectionName))
                .eq(Assignment::getId, id);
        AssignmentDetailsVo assignmentDetailsVo = assignmentMapper.selectJoinOne(AssignmentDetailsVo.class, wrapper);


        LambdaQueryWrapper<AssignmentWithDisease> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(AssignmentWithDisease::getDiseaseId);
        queryWrapper.eq(AssignmentWithDisease::getAssignmentId, id);
        List<AssignmentWithDisease> list = awdService.list(queryWrapper);
        List<String> ids = list.stream().map(AssignmentWithDisease::getDiseaseId).toList();
        assignmentDetailsVo.setDiseaseRegistrationIds(ids);

        if (!ids.isEmpty()) {
            MPJLambdaWrapper<Disease> wrapper1 = new MPJLambdaWrapper<Disease>()
                    .select(Disease::getDiseaseName)
                    .rightJoin(DiseaseRegistration.class, DiseaseRegistration::getDisease, Disease::getId)
                    .in(DiseaseRegistration::getId, ids);
            List<Disease> diseases = diseaseService.list(wrapper1);
            List<String> listNames = diseases.stream().map(Disease::getDiseaseName).toList();
            assignmentDetailsVo.setDiseaseRegistrationNames(listNames);
        }
        return ResultUtil.success(assignmentDetailsVo);
    }

    @Operation(summary = "根据id审核任务信息")
    @GetMapping("/examineById")
    public Result<String> examineById(@RequestParam("id") String id,
                                      @Schema(description = "审核状态，1审核通过，2审核不通过") @RequestParam("isAgree") int is_agree,
                                      @Schema(description = "审核说明") @RequestParam("auditInstructions") String auditInstructions,
                                      @Schema(description = "审核人id") @RequestParam(value = "apId" ,required = false) String apId) {

        LambdaUpdateWrapper<Assignment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Assignment::getId, id).set(Assignment::getAuditStatus, is_agree).set(Assignment::getAuditInstructions, auditInstructions).set(Assignment::getAuditTime,new Date());

        boolean update = assignmentService.update(updateWrapper);
        if (update) {


            if(StringUtils.isNotEmpty(apId)) assignmentApprovalHistoryService.saveApprovalHistory(1, auditInstructions, apId, id);

            return ResultUtil.success("审核成功");
        }
        return ResultUtil.fail("审核失败");
    }

    @Operation(summary = "查询任务信息列表")
    @PostMapping("/getList")
    public Result<Page<AssignmentListVo>> getList(@RequestBody SelectAssignmentDto selectAssignmentDto) {

        MPJLambdaWrapper<Assignment> queryWrapper = assignmentService.getMPJWrapper()
                .select("(SELECT count(*) from assignment_with_disease awd  where awd.assignment_id = t.id)  diseaseCount")
                .apply("1=1")
                .in(!selectAssignmentDto.getAuditStatus().isEmpty(), Assignment::getAuditStatus, selectAssignmentDto.getAuditStatus())
                .eq(StringUtils.isNotEmpty(selectAssignmentDto.getStatus()), Assignment::getStatus, selectAssignmentDto.getStatus())
                .eq(StringUtils.isNotEmpty(selectAssignmentDto.getDiseaseModule()), Assignment::getDiseaseModule, selectAssignmentDto.getDiseaseModule())
                .eq(StringUtils.isNotEmpty(selectAssignmentDto.getTaskOrderNumber()), Assignment::getTaskOrderNumber, selectAssignmentDto.getTaskOrderNumber())
                .eq(StringUtils.isNotEmpty(selectAssignmentDto.getMaintenanceUnitId()), Assignment::getMaintenanceUnitId, selectAssignmentDto.getMaintenanceUnitId())
                .ge(selectAssignmentDto.getDispatchStartDate() != null, Assignment::getDispatchDate, selectAssignmentDto.getDispatchStartDate())
                .le(selectAssignmentDto.getDispatchEndDate() != null, Assignment::getDispatchDate, selectAssignmentDto.getDispatchEndDate())
                .orderByDesc(Assignment::getPublishTime);
        if (StringUtils.isNotEmpty(selectAssignmentDto.getSectionId())) {
            queryWrapper.leftJoin(InspectionRegistration.class, InspectionRegistration::getId, Assignment::getInspectionInfo)
                    .eq(InspectionRegistration::getSectionId, selectAssignmentDto.getSectionId());
        }


        Page<AssignmentListVo> assignmentListVoPage = assignmentMapper.selectJoinPage(new Page<>(selectAssignmentDto.getPageIndex(), selectAssignmentDto.getPageSize()), AssignmentListVo.class, queryWrapper);
        return ResultUtil.success(assignmentListVoPage);
    }

    @Operation(summary = "根据id获取作业管理施工维修详细信息")
    @GetMapping("/getJobManagementInfoById")
    public Result<JobCMVo> getJobManagementInfo(@RequestParam("id") String id) {

        MPJLambdaWrapper<Assignment> queryWrapper = assignmentService.getMPJWrapper()
                .eq(Assignment::getId, id);
        AssignmentListVo assignmentListVo = assignmentMapper.selectJoinOne(AssignmentListVo.class, queryWrapper);

        MPJLambdaWrapper<AssignmentWithDisease> AWDMPJLambdaWrapper = assignmentService.getDetailMPJWrapper()
                .leftJoin(Dictionary.class,Dictionary::getId,DiseaseRegistration::getDirection,ext ->
                        ext.selectAs(Dictionary::getValusas,AwdWithDiseaseVo::getDirectionName))
                .leftJoin(Dictionary.class,Dictionary::getId,DiseaseRegistration::getLane,ext ->
                        ext.selectAs(Dictionary::getValusas,AwdWithDiseaseVo::getLaneName))
                .leftJoin(Section.class,Section::getId,DiseaseRegistration::getRoute,ext ->
                        ext.selectAs(Section::getSectionName,AwdWithDiseaseVo::getRouteName))

                .eq(AssignmentWithDisease::getAssignmentId, id);
        List<AwdWithDiseaseVo> jobCMVos = assignmentWithDiseaseMapper.selectJoinList(AwdWithDiseaseVo.class, AWDMPJLambdaWrapper);

        MPJLambdaWrapper<EngineeringQualityInfo> wrapper = new MPJLambdaWrapper<EngineeringQualityInfo>()
                .selectAll(EngineeringQualityInfo.class)

                .leftJoin(MaintenanceContent.class, MaintenanceContent::getId, EngineeringQualityInfo::getMcId, ext ->
                        ext.selectAs(MaintenanceContent::getContentName, EQIListVo::getContentName))
                .leftJoin(ConstructionIndicators.class, ConstructionIndicators::getId, EngineeringQualityInfo::getCiId, ext ->
                        ext.selectAs(ConstructionIndicators::getIndicatorsName, EQIListVo::getIndicatorsName))
                .leftJoin(ConstructionIndexItems.class, ConstructionIndexItems::getId, EngineeringQualityInfo::getCiiId, ext ->
                        ext.selectAs(ConstructionIndexItems::getIndexItemsName, EQIListVo::getIndexItemsName))

                .leftJoin(EqiWithDr.class,EqiWithDr::getEqiId,EngineeringQualityInfo::getId)
                .leftJoin(DiseaseRegistration.class,DiseaseRegistration::getId,EqiWithDr::getDiseaseRegistrationId,ext ->
                        ext.selectAs(DiseaseRegistration::getPublishTime,EQIListVo::getDrPublishTime))


                .eq(EngineeringQualityInfo::getJobManagementId, id);
        List<EQIListVo> eqiListVos = engineeringQualityInfoService.selectJoinList(EQIListVo.class, wrapper);

        if (!eqiListVos.isEmpty()) {
            List<String> EqiIds = eqiListVos.stream().map(EQIListVo::getId).toList();

            MPJLambdaWrapper<EqiWithDr> wrapper2 = new MPJLambdaWrapper<EqiWithDr>()
                    .select(EqiWithDr::getEqiId, EqiWithDr::getDiseaseRegistrationId)
                    .leftJoin(DiseaseRegistration.class, DiseaseRegistration::getId, EqiWithDr::getDiseaseRegistrationId)
                    .leftJoin(Disease.class,Disease::getId, DiseaseRegistration::getDisease,ext ->
                            ext.selectAs(Disease::getDiseaseName, EqiWithDiseaseVo::getDiseaseName))
                    .in(EqiWithDr::getEqiId, EqiIds);
            List<EqiWithDiseaseVo> list = eqiWithDrService.selectJoinList(EqiWithDiseaseVo.class, wrapper2);

            LambdaQueryWrapper<EqiWithTp> wrapper1 = new LambdaQueryWrapper<EqiWithTp>()
                    .in(EqiWithTp::getEqiId, EqiIds);
            List<EqiWithTp> eqiWithTps = eqiWithTpMapper.selectList(wrapper1);

            for (EQIListVo eqiListVo : eqiListVos) {
                List<EqiWithDiseaseVo> list1 = list.stream().filter(EqiWithDr -> EqiWithDr.getEqiId().equals(eqiListVo.getId())).toList();
                eqiListVo.setDiseaseIds(list1.stream().map(EqiWithDiseaseVo::getDiseaseRegistrationId).toList());
                eqiListVo.setDiseaseNames(list1.stream().map(EqiWithDiseaseVo::getDiseaseName).toList());
                eqiListVo.setEqiWithTpDtoList(eqiWithTps.stream().filter(eqiWithTp -> eqiWithTp.getEqiId().equals(eqiListVo.getId())).toList());

                if (eqiListVo.getDrPublishTime() != null && assignmentListVo.getRepairCompletionTime() != null) {
                    Instant instant1 = eqiListVo.getDrPublishTime().toInstant();
                    Instant instant2 = assignmentListVo.getRepairCompletionTime().toInstant();
                    Duration duration = Duration.between(instant1, instant2);
                    double da =  duration.toHours() + duration.toMinutesPart() / 60.0;
                    eqiListVo.setMaintenanceTime(String.format("%.2f", da < 0 ? 0 : da));
                }
            }

        }

        MPJLambdaWrapper<BillOfQuantities> wrapper1 = new MPJLambdaWrapper<BillOfQuantities>()
                .selectAll(BillOfQuantities.class)
                .leftJoin(PlanMetering.class,PlanMetering::getId,BillOfQuantities::getMcId)
                .leftJoin(MeteringInventory.class, MeteringInventory::getId, PlanMetering::getMeteringInventoryId, ext ->
                        ext.selectAs(MeteringInventory::getProjectName, BOQListVo::getProjectName))
                .eq(BillOfQuantities::getJobManagementId, id);
        List<BOQListVo> boqListVos = billOfQuantitiesMapper.selectJoinList(BOQListVo.class, wrapper1);

        if (!boqListVos.isEmpty()) {
            List<String> list1 = boqListVos.stream().map(BOQListVo::getId).toList();

            MPJLambdaWrapper<BopWithDr> wrapper2 = new MPJLambdaWrapper<BopWithDr>()
                    .select(BopWithDr::getDiseaseRegistrationId, BopWithDr::getBoqId)
                    .leftJoin(DiseaseRegistration.class, DiseaseRegistration::getId, EqiWithDr::getDiseaseRegistrationId)
                    .leftJoin(Disease.class,Disease::getId, DiseaseRegistration::getDisease,ext ->
                            ext.selectAs(Disease::getDiseaseName, BopWithDrDiseaseVo::getDiseaseName))
                    .in(BopWithDr::getBoqId, list1);
            List<BopWithDrDiseaseVo> list2 = bopWithDrService.selectJoinList(BopWithDrDiseaseVo.class, wrapper2);

            for (BOQListVo boqListVo : boqListVos) {
                List<BopWithDrDiseaseVo> list3 = list2.stream().filter(BopWithDr -> BopWithDr.getBoqId().equals(boqListVo.getId())).toList();
                boqListVo.setDiseaseIds(list3.stream().map(BopWithDrDiseaseVo::getDiseaseRegistrationId).toList());
                boqListVo.setDiseaseNames(list3.stream().map(BopWithDrDiseaseVo::getDiseaseName).toList());
            }
        }

        JobCMVo jobCMVo = new JobCMVo();
        jobCMVo.setAssignmentListVo(assignmentListVo);
        jobCMVo.setAwdWithDiseaseVo(jobCMVos);
        jobCMVo.setEqiListVo(eqiListVos);
        jobCMVo.setBoqListVo(boqListVos);

        return ResultUtil.success(jobCMVo);
    }

    @Operation(summary = "根据id获取任务关联病害详细信息")
    @GetMapping("/getDetailById")
    public Result<JobCMVo> getDetailById(@RequestParam("id") String id) {

        MPJLambdaWrapper<AssignmentWithDisease> AWDMPJLambdaWrapper = assignmentService.getDetailMPJWrapper()
                .leftJoin(Dictionary.class,Dictionary::getId,DiseaseRegistration::getDirection,ext ->
                        ext.selectAs(Dictionary::getValusas,AwdWithDiseaseVo::getDirectionName))
                .leftJoin(Dictionary.class,Dictionary::getId,DiseaseRegistration::getLane,ext ->
                        ext.selectAs(Dictionary::getValusas,AwdWithDiseaseVo::getLaneName))
                .leftJoin(Section.class,Section::getId,DiseaseRegistration::getRoute,ext ->
                        ext.selectAs(Section::getSectionName,AwdWithDiseaseVo::getRouteName))

                .eq(AssignmentWithDisease::getAssignmentId, id);
        List<AwdWithDiseaseVo> jobCMVos = assignmentWithDiseaseMapper.selectJoinList(AwdWithDiseaseVo.class, AWDMPJLambdaWrapper);

        JobCMVo jobCMVo = new JobCMVo();
        jobCMVo.setAwdWithDiseaseVo(jobCMVos);

        return ResultUtil.success(jobCMVo);
    }


    @Operation(summary = "根据任务id获取审批历史")
    @GetMapping("/getApprovalHistory")
    public Result<Page<ApprovalHistoryListVo>> getApprovalHistory(@RequestParam("pageIndex") int pageIndex, @RequestParam("pageSize") int pageSize, @RequestParam("id") String id) {

        MPJLambdaWrapper<AssignmentApprovalHistory> wrapper = assignmentApprovalHistoryService.getMPJWrapper()
                .eq(AssignmentApprovalHistory::getAssignmentId, id)
                .orderByDesc(AssignmentApprovalHistory::getApprovalTime);

        Page<ApprovalHistoryListVo> approvalHistoryListVoPage = assignmentApprovalHistoryService.selectJoinListPage(new Page<>(pageIndex, pageSize), ApprovalHistoryListVo.class, wrapper);

        return ResultUtil.success(approvalHistoryListVoPage);
    }


    @Operation(summary = "养护数据对比")
    @GetMapping("/getMaintenanceDataContrast")
    public Result<List<MaintenanceDataContrastVo>> getMaintenanceDataContrast(){

        MPJLambdaWrapper<Assignment> wrapper = new MPJLambdaWrapper<Assignment>()
                .selectAs(Assignment::getDiseaseModule,MaintenanceDataContrastVo::getDiseaseModule)
                .selectAs("sum(nums)",MaintenanceDataContrastVo::getQuantityOfWork)
                .selectAs("sum(nums * unit_price)",MaintenanceDataContrastVo::getCost)
                .leftJoin(BillOfQuantities.class,BillOfQuantities::getJobManagementId,Assignment::getId)
                .apply("1=1")
                .groupBy(Assignment::getDiseaseModule);
        List<MaintenanceDataContrastVo> maintenanceDataContrastVos = assignmentService.selectJoinList(MaintenanceDataContrastVo.class, wrapper);

        List<MaintenanceDataContrastVo> maintenanceDataContrastVos1 = new ArrayList<>();
        MaintenanceDataContrastVo maintenanceDataContrastVo;
        List<Map<String, String>> dModel = NoCode.getDModel();

        for (Map<String, String> item : dModel){
            maintenanceDataContrastVo = new MaintenanceDataContrastVo();
            String diseaseModule = item.get("dModel");
            String diseaseModuleName = item.get("name");

            maintenanceDataContrastVo.setDiseaseModule(diseaseModule);
            maintenanceDataContrastVo.setDiseaseModuleName(diseaseModuleName);

            List<MaintenanceDataContrastVo> list = maintenanceDataContrastVos.stream().filter(f -> f.getDiseaseModule().equals(diseaseModule)).toList();
            if(!list.isEmpty()){
                maintenanceDataContrastVo.setQuantityOfWork(list.getFirst().getQuantityOfWork());
                maintenanceDataContrastVo.setCost(list.getFirst().getCost());
            }
            maintenanceDataContrastVos1.add(maintenanceDataContrastVo);
        }

        return ResultUtil.success(maintenanceDataContrastVos1);
    }


    @Operation(summary = "历年维修费用")
    @GetMapping("/getAnnualMaintenanceCosts")
    public Result<AMCVo> getAnnualMaintenanceCosts(){
        // 当前时间（包含时区信息）
        ZonedDateTime currentTime = ZonedDateTime.now();
        ZonedDateTime fiveYearsAgo = currentTime.minusYears(3);
        // 转换为 Date 类型（如果需要）
        Date dateFiveYearsAgo = Date.from(fiveYearsAgo.toInstant());


        MPJLambdaWrapper<Assignment> wrapper = new MPJLambdaWrapper<Assignment>()
                .selectAs("sum(t1.nums * t1.unit_price)",AnnualMaintenanceCostsVo::getMaintenanceCosts)
                .selectAs(Plan::getSectionId,AnnualMaintenanceCostsVo::getSectionId)
                .selectAs("DATE_FORMAT(t.publish_time,'%Y')",AnnualMaintenanceCostsVo::getDate)

                .leftJoin(BillOfQuantities.class,BillOfQuantities::getJobManagementId,Assignment::getId)
                .leftJoin(PlanMetering.class,PlanMetering::getId,BillOfQuantities::getMcId)
                .leftJoin(Plan.class,Plan::getId,PlanMetering::getPlanId)


                .eq(Assignment::getAuditStatus,5).gt(Assignment::getPublishTime,dateFiveYearsAgo)

                .groupBy(AnnualMaintenanceCostsVo::getSectionId,AnnualMaintenanceCostsVo::getDate);

        List<AnnualMaintenanceCostsVo> annualMaintenanceCostsVos = assignmentService.selectJoinList(AnnualMaintenanceCostsVo.class, wrapper);



        MPJLambdaWrapper<Section> wrapper1 = new MPJLambdaWrapper<Section>()
                .selectAs(Section::getId,SectionListVo::getId)
                .selectAs(Section::getRouteId,SectionListVo::getRouteId)
                .selectAs(Route::getRouteName,SectionListVo::getRouteName)
                .leftJoin(Route.class,Route::getId,Section::getRouteId)
                .apply("1=1");
        List<SectionListVo> sectionListVos = sectionService.selectJoinList(SectionListVo.class, wrapper1);
        Map<String, List<SectionListVo>> collect = sectionListVos.stream().collect(Collectors.groupingBy(SectionListVo::getRouteId));


        AMCVo amcVo = new AMCVo();
        List<AMCData> amcDataList = new ArrayList<>();
        AMCData amcData;
        for (int i = currentTime.getYear(); i > fiveYearsAgo.getYear(); i--) {
            String year = String.valueOf(i);
            List<AnnualMaintenanceCostsVo> list = annualMaintenanceCostsVos.stream().filter(f -> f.getDate().equals(year)).toList();

            amcData = new AMCData();
            amcData.setYear(year);


            if (i == currentTime.getYear()) {
                amcVo.setThisYearsExpenses(list.stream().mapToDouble(AnnualMaintenanceCostsVo::getMaintenanceCosts).sum());
            } else if (i == currentTime.getYear() - 1) {
                amcVo.setPreviousYearExpenses(list.stream().mapToDouble(AnnualMaintenanceCostsVo::getMaintenanceCosts).sum());
            }


            List<AMCRoute> amcRouteList = new ArrayList<>();
            collect.forEach((key, value) -> {
                AMCRoute amcRoute = new AMCRoute();
                amcRoute.setRouteId(key);
                amcRoute.setRouteName(value.getFirst().getRouteName());

                if (!list.isEmpty()) {
                    List<String> sectionIds = value.stream().map(SectionListVo::getId).toList();
                    List<AnnualMaintenanceCostsVo> list1 = list.stream().filter(f -> sectionIds.contains(f.getSectionId())).toList();
                    if (!list1.isEmpty()) {
                        amcRoute.setCost(list1.stream().mapToDouble(AnnualMaintenanceCostsVo::getMaintenanceCosts).sum());
                    }
                }
                amcRouteList.add(amcRoute);
            });

            amcData.setAmcRouteInfo(amcRouteList);
            amcDataList.add(amcData);
        }

        amcVo.setAmcDataList(amcDataList);
        amcVo.calculatePhaseDifference();
        return ResultUtil.success(amcVo);
    }


    @Operation(summary = "任务进度查询")
    @GetMapping("/getAssignmentProgress")
    public Result<AssignmentProgressVos>  getAssignmentProgress(@RequestParam("id") String id){

        CompletableFuture<List<DRInfo>> drInfo = awdService.getDRInfo(id);
        CompletableFuture<List<IRInfo>> irInfo = awdService.getIRInfo(id);
        CompletableFuture<List<RepairInformationInfo>> repairInformationInfo = awdService.getRepairInformationInfo(id);
        CompletableFuture<AssignmentInfo> assignmentInfo = assignmentService.getAssignmentInfo(id);
        CompletableFuture<List<EqiWithTp>> acceptanceInfos = engineeringQualityInfoService.getAcceptanceInfos(id);
        CompletableFuture<CheckAcceptInfo> checkAcceptInfo = assignmentApprovalHistoryService.getCheckAcceptInfo(id);
        CompletableFuture<List<MaintenanceMeteringInfo>> meteringInfo = billOfQuantitiesService.getMeteringInfo(id);
        CompletableFuture<List<ComponentsInfo>> componentsInfos = awdService.getComponentsInfos(id);

        CompletableFuture.allOf(drInfo,irInfo,assignmentInfo,repairInformationInfo,
                acceptanceInfos,checkAcceptInfo,meteringInfo,componentsInfos).join();

        List<DRInfo> drInfos = drInfo.join();
        List<IRInfo> irInfos = irInfo.join();
        for (IRInfo irIn : irInfos){
            irIn.setDrInfos(drInfos.stream().filter(f -> f.getIRId().equals(irIn.getId())).toList());
        }

        CheckAcceptInfo CAInfo = checkAcceptInfo.join();
        List<RepairInformationInfo> repairInformationInfoList = repairInformationInfo.join();
        List<EqiWithTp> eqiWithTps = acceptanceInfos.join();
        if(!eqiWithTps.isEmpty()){
            //复用验收信息
            if(CAInfo != null){
                CAInfo.setAcceptanceInfos(eqiWithTps);
                if(!repairInformationInfoList.isEmpty()){
                    CAInfo.setIndicatorsName(repairInformationInfoList.getFirst().getIndicatorsName());
                    CAInfo.setIndexItemsName(repairInformationInfoList.getFirst().getIndexItemsName());
                    CAInfo.setConstructionMaterials(repairInformationInfoList.getFirst().getConstructionMaterials());
                    CAInfo.setAppearanceAppraisal(repairInformationInfoList.getFirst().getAppearanceAppraisal());
                    CAInfo.setImg(repairInformationInfoList.getFirst().getAfterRepairImg());
                }
            }

            //设置对应维修信息的实测项目信息
            repairInformationInfoList.forEach(item -> item.setAcceptanceInfos(eqiWithTps.stream().filter(f -> f.getEqiId().equals(item.getEqiId())).toList()));
        }

        AssignmentProgressVos assignmentProgressVos = new AssignmentProgressVos();
        assignmentProgressVos.setIrInfos(irInfos);
        assignmentProgressVos.setAssignmentInfo(assignmentInfo.join());
        assignmentProgressVos.setRepairInformationInfo(repairInformationInfoList);
        assignmentProgressVos.setCheckAcceptInfo(CAInfo);
        MeteringInfo meteringInfos = new MeteringInfo();
        meteringInfos.setMaintenanceMeteringInfo(meteringInfo.join());
        meteringInfos.setComponentsInfos(componentsInfos.join());
        assignmentProgressVos.setMeteringInfo(meteringInfos);

        return ResultUtil.success(assignmentProgressVos);
    }


}